<template>
	<div class="table-search-container">
		<el-form
			ref="tableSearchRef"
			class="table-form"
			:model="state.ruleForm"
			:size="themeConfig.globalComponentSize"
			label-width="auto"
		>
			<el-row :gutter="12">
				<TransitionGroup name="search">
					<template v-for="(val, key) in tableSearch">
						<el-col
							v-if="!val.isHide"
							v-show="key === 0 || state.isToggle"
							:key="val.prop"
							:xs="24"
							:sm="12"
							:md="val.type.includes('multi') || val.type.includes('Range') ? 12 : 8"
							:lg="val.type.includes('multi') || val.type.includes('Range') ? 8 : 6"
							:xl="val.type.includes('multi') || val.type.includes('Range') ? 6 : 4"
							class="mb10"
						>
							<el-form-item
								:label="val.label"
								:prop="val.prop"
								:rules="[
									{
										required: val.required,
										message: `${val.label}不能为空`,
										trigger: val.type === 'input' ? 'blur' : 'change',
									},
								]"
							>
								<el-input
									v-if="val.type === 'input'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									clearable
									style="width: 100%"
								/>
								<el-input-number
									v-else-if="val.type === 'number'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									:min="val.min"
									:max="val.max"
									:step="val.step"
									:precision="val.precision"
									style="width: 100%"
								/>
								<el-select
									v-else-if="val.type === 'select'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									style="width: 100%"
								>
									<el-option
										v-for="item in val.options"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									>
									</el-option>
								</el-select>
								<el-select
									v-else-if="val.type === 'multiSelect'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									multiple
									clearable
									style="width: 100%"
								>
									<el-option
										v-for="item in val.options"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									>
									</el-option>
								</el-select>
								<el-tree-select
									v-else-if="val.type === 'treeSelect'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									:data="val.options || []"
									:props="
										val.treeProps || {
											label: 'label',
											value: 'id',
											children: 'children',
											disabled: 'disabled',
										}
									"
									:check-strictly="val.isCheckStrictly"
									:filter-node-method="(value: string, data: EmptyObjectType) => filterTreeNode(value, data, val.treeProps)"
									filterable
									clearable
									node-key="id"
									style="width: 100%"
								/>
								<el-date-picker
									v-else-if="val.type === 'date'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									type="date"
									style="width: 100%"
								/>
								<el-time-picker
									v-else-if="val.type === 'time'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									style="width: 100%"
								/>
								<el-cascader
									v-else-if="val.type === 'cascader'"
									v-model="state.ruleForm[val.prop]"
									:options="val.options || []"
									:props="{
										expandTrigger: 'hover',
										value: 'value',
										label: 'label',
										children: 'children',
									}"
									:placeholder="val.placeholder"
									filterable
									clearable
									style="width: 100%"
								/>
								<el-date-picker
									v-else-if="val.type === 'datetime'"
									v-model="state.ruleForm[val.prop]"
									:placeholder="val.placeholder"
									type="datetime"
									style="width: 100%"
								/>
								<el-date-picker
									v-else-if="val.type === 'dateRange'"
									v-model="state.ruleForm[val.prop]"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									type="daterange"
									style="width: 100%"
								/>
								<el-time-picker
									v-else-if="val.type === 'timeRange'"
									v-model="state.ruleForm[val.prop]"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									is-range
									style="width: 100%"
								/>
								<el-date-picker
									v-else-if="val.type === 'datetimeRange'"
									v-model="state.ruleForm[val.prop]"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									type="datetimerange"
									style="width: 100%"
								/>
								<el-rate
									v-else-if="val.type === 'rate'"
									v-model="state.ruleForm[val.prop]"
									:colors="['#99A9BF', '#F7BA2A', '#FF9900']"
									size="default"
									clearable
									allow-half
									show-score
									score-template="{value} 星"
									style="width: 100%"
								/>
							</el-form-item>
						</el-col>
					</template>
				</TransitionGroup>
				<el-col :xs="24" :sm="12" :md="8" :lg="4" class="mb10">
					<el-form-item
						class="table-form-btn"
						:label-width="showExpand && tableSearch.length > 1 ? 'auto' : '0'"
					>
						<template #label v-if="showExpand && tableSearch.length > 1">
							<div class="table-form-btn-toggle" @click="state.isToggle = !state.isToggle">
								<HIcon :name="state.isToggle ? 'ele-ArrowUp' : 'ele-ArrowDown'" />&nbsp;
								<span>{{ state.isToggle ? "收起" : "展开" }}</span>
							</div>
						</template>
						<div style="display: flex">
							<el-button type="primary" @click="onSearch(tableSearchRef)">查询</el-button>
							<el-button type="info" @click="onReset(tableSearchRef)">重置</el-button>
							<slot></slot>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>

<script setup lang="ts" name="tableSearch">
import { reactive, ref, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "/@/stores/themeConfig";

// 定义父组件传过来的值
interface TableSearchProps {
	tableSearch: TableSearchType[]; // 搜索表单配置项
	initToggle?: boolean; // 初始化时搜索表单是否展开
	showExpand?: boolean; // 是否显示展开按钮
}
const props = withDefaults(defineProps<TableSearchProps>(), {
	initToggle: false,
	showExpand: true,
});

// 定义父组件可触发的事件
const emit = defineEmits(["search"]);

// 定义变量内容
const { themeConfig } = storeToRefs(useThemeConfig());
const tableSearchRef = ref<FormInstance>();
const state = reactive({
	ruleForm: {},
	isToggle: props.initToggle,
});

// 查询
const onSearch = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (valid) {
			emit("search", JSON.parse(JSON.stringify(state.ruleForm)));
		}
	});
	console.log("onSearch", state.ruleForm);
};
// 重置
const onReset = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	emit("search", state.ruleForm, true);
};
// treeSelect 过滤方法
const filterTreeNode = (value: string, data: EmptyObjectType, treeProps?: EmptyObjectType) => {
	if (!value) return true;
	return data[treeProps?.label || "label"].includes(value);
};
// 初始化 form 字段
const initFormField = () => {
	if (props.tableSearch.length === 0) return;
	props.tableSearch.filter(v => !v.isHide).forEach(v => (state.ruleForm[v.prop] = v.defaultValue || ""));
};
// 页面加载时
onMounted(() => {
	initFormField();
});
</script>

<style scoped lang="scss">
.table-search-container {
	display: flex;
	.table-form {
		flex: 1;
		.table-form-btn-toggle {
			white-space: nowrap;
			user-select: none;
			display: flex;
			align-items: center;
			color: var(--el-color-primary);
			cursor: pointer;
		}
	}
}

/* TransitionGroup name="search" */
.search-enter-active,
.search-leave-active {
	transition: all 0.1s ease;
}
.search-enter-from,
.search-leave-to {
	transform: translateX(-30px);
	opacity: 0;
}
</style>
